﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using PropertyManagment.common.lang;
using PropertyManagment.controllers;
using PropertyManagment.entity;
using PropertyManagment.entity.dto;
using PropertyManagment.service;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace PropertyManagment.controllers {

    /// <summary>
    /// 角色控制器
    /// </summary>
    public class SysRoleController : BaseController<SysRole> {

        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="name">角色名</param>
        /// <response code="200">返回角色列表</response>
        /// <returns></returns>
        [HttpGet]
        [Route("/sys/role/list")]
        [Authorize(Roles = "sys:role:list")]
        public Result list(string name){
            Page<SysRole> pageData = sysRoleService.page(getPage(),
                string.IsNullOrWhiteSpace(name) ? sysRoleService.getAll() : sysRoleService.getAll().Where(r => r.name.Contains(name)).ToList());
            return Result.succ(pageData);
        }

        /// <summary>
        /// 角色过滤列表
        /// </summary>
        /// <response code="200">返回角色拥有权限的列表</response>
        /// <returns></returns>
        [HttpGet]
        [Route("/sys/role/filterList")]
        [Authorize(Roles = "sys:role:list")]
        public Result filterList() {
            var roleList = sysRoleService.getAll();
            SysUser user = sysUserService.getByUsername(HttpContext.User.Identity.Name);
            string authorityInfo = sysUserService.getUserAuthorityInfo(user.id);
            //如果不是超级管理员,则过滤掉 超级管理员 和 管理员权限
            if (!authorityInfo.Contains("ROLE_admin")) {
                roleList = roleList.Where<SysRole>(r => !r.name.Equals("超级管理员") && !r.name.Equals("管理员")).ToList();
            }
            return Result.succ(roleList);
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="sysRole">角色信息</param>
        /// <response code="200">返回角色信息</response>
        /// <returns></returns>
        [HttpPost]
        [Route("/sys/role/save")]
        [Authorize(Roles = "sys:role:save")]
        public Result save([FromBody] SysRole sysRole) {
            try {
                sysRole.created = DateTime.Now;
                sysRoleService.add(sysRole);
                return Result.succ(sysRole);
            } catch {
                return Result.fail("添加角色失败，名称或者编码已经存在！");
            }
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="sysRole">角色信息</param>
        /// <response code="200">返回角色信息</response>
        /// <returns></returns>
        [HttpPost]
        [Route("/sys/role/update")]
        [Authorize(Roles = "sys:role:update")]
        public Result update([FromBody] SysRole sysRole) {
            sysRole.updated = DateTime.Now;
            sysRoleService.update(sysRole);
            // 更新缓存
            sysUserService.clearUserAuthorityInfoByRoleId(sysRole.id);
            return Result.succ(sysRole);
        }

        /// <summary>
        /// 单个角色信息
        /// </summary>
        /// <param name="id">角色id</param>
        /// <response code="200">返回角色信息</response>
        /// <response code="404">如果id为空</response>
        /// <returns></returns>
        [HttpGet]
        [Route("/sys/role/info/{id}")]
        [Authorize(Roles = "sys:role:list")]
        public Result info(long id) {
            SysRole sysRole = sysRoleService.getById(id);
            // 获取角色相关联的菜单id
            var roleMenus = sysRoleMenuService.getAll().Where(rm=>rm.role_id==id).ToList();
            List<long> menuIds = roleMenus.Select(rm => rm.menu_id).ToList();
            sysRole.menuIds.AddRange(menuIds);
            return Result.succ(sysRole);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="ids">角色id</param>
        /// <response code="200">删除成功</response>
        /// <returns></returns>
        [HttpPost]
        [Route("/sys/role/delete")]
        [Authorize(Roles = "sys:role:delete")]
        public Result info([FromBody] long[] ids) {
            sysRoleService.deleteByIds(ids);
            // 删除中间表
            sysUserRoleService.deleteList(sysUserRoleService.getAll().Where(ur => ids.Contains(ur.role_id)).ToList());
            sysRoleMenuService.deleteList(sysRoleMenuService.getAll().Where(ur => ids.Contains(ur.role_id)).ToList());
            // 缓存同步删除
            ids.ToList().ForEach(id =>
                // 更新缓存
                sysUserService.clearUserAuthorityInfoByRoleId(id)
            );
            return Result.succ("删除成功");
        }

        /// <summary>
        /// 更新角色权限
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <param name="menuIds">菜单id</param>
        /// <response code="200">返回角色的菜单权限id</response>
        /// <response code="404">如果id为空</response>
        /// <returns></returns>
        [HttpPost]
        [Route("/sys/role/perm/{roleId}")]
        [Authorize(Roles = "sys:role:perm")]
        public Result info(long roleId, [FromBody] long[] menuIds) {
            List<SysRoleMenu> sysRoleMenus = new List<SysRoleMenu>();
            menuIds.ToList().ForEach(menuId => {
                SysRoleMenu roleMenu = new SysRoleMenu();
                roleMenu.menu_id = menuId;
                roleMenu.role_id = roleId;
                sysRoleMenus.Add(roleMenu);
            });
            // 先删除原来的记录，再保存新的
            //Debug.WriteLine(sysRoleMenuService.getAll().Where(rm => rm.role_id == roleId).ToList());
            sysRoleMenuService.deleteList(sysRoleMenuService.getAll().Where(rm => rm.role_id == roleId).ToList());
            sysRoleMenuService.addList(sysRoleMenus);
            // 删除缓存
            sysUserService.clearUserAuthorityInfoByRoleId(roleId);
            return Result.succ(menuIds);
        }
    }
}
